#!/usr/bin/python3

# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import parent
from testlib import *


def wait_dashboard_addresses(b, expected):
    b.wait_js_func(
        """(function(expected) {
            var nodes = document.querySelectorAll('#dashboard-hosts .list-group-item');
            var addresses = Array.prototype.map.call(nodes, function(e) {
                return e.getAttribute("data-address");
            });
            return expected.sort().toString() == addresses.sort().toString();
        })""", expected)


def add_machine(b, address):
    b.click('#dashboard-add')
    b.wait_popup('dashboard_setup_server_dialog')
    b.set_val('#add-machine-address', address)

    b.wait_text('#dashboard_setup_server_dialog .btn-primary', "Add")
    b.click('#dashboard_setup_server_dialog .btn-primary')
    b.wait_in_text('#dashboard_setup_server_dialog', "Fingerprint")
    b.click('#dashboard_setup_server_dialog .btn-primary')
    b.wait_popdown('dashboard_setup_server_dialog')


class TestMultiOS(MachineCase):
    provision = {
        "0": {"address": "10.111.113.1/20"},
        "fedora-23-stock": {"address": "10.111.113.5/20", "image": "fedora-23-stock"}
    }

    def check_spawn(self, b, address):
        # Firefox cannot do `cockpit.spawn` as it returns promise
        if b.cdp.browser == "firefox":
            return
        result = b.call_js_func("""(function(address) {
            return cockpit.spawn(['echo', 'hi'], { host: address });
        })""", address)
        self.assertEqual(result, "hi\n")

    def check_dbus(self, b, address):
        b.call_js_func("""(function(address) {
            return cockpit.dbus("org.freedesktop.DBus", { host: address })
                .proxy("org.freedesktop.DBus", "/").call("GetId");
        })""", address)

    def testFedora23(self):
        dev_m = self.machine
        dev_b = self.browser

        # Newer bridges running under an old cockpit-ws don't get the
        # support that they need to prompt for the password. So open
        # up sudo for this test.
        dev_m.execute("echo '%wheel ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers.d/user-override")
        dev_m.execute("echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers.d/user-override")

        self.allow_hostkey_messages()

        self.login_and_go("/dashboard")

        dev_dashboard_addresses = ["localhost"]
        wait_dashboard_addresses(dev_b, dev_dashboard_addresses)

        def stock_login_and_go(browser, page, href):
            browser.open(href)
            browser.wait_visible("#login")
            browser.set_val('#login-user-input', browser.default_user)
            browser.set_val('#login-password-input', "foobar")
            browser.click('#login-button')
            browser.expect_load()
            browser.wait_visible('#content')
            if page:
                stock_enter_page(browser, page)

        def stock_enter_page(browser, page):
            frame = "cockpit1:localhost/" + page
            browser.switch_to_top()
            browser.wait_present("iframe.container-frame[name='%s'][data-loaded]" % frame)
            browser.wait_visible("iframe.container-frame[name='%s']" % frame)
            browser.switch_to_frame(frame)
            browser.wait_visible('#' + page)

        stock_m = self.machines['fedora-23-stock']

        # Wait for connectivity between the two
        wait(lambda: stock_m.execute("ip addr >&2 && ping -q -w5 -c5 10.111.113.1"))
        wait(lambda: dev_m.execute("ip addr  >&2 && ping -q -w5 -c5 10.111.113.5"))

        stock_m.execute("hostnamectl set-hostname stock")
        stock_b = self.new_browser(stock_m)

        stock_login_and_go(stock_b, "dashboard", href="/dashboard")
        wait_dashboard_addresses(stock_b, ["localhost"])

        add_machine(stock_b, "10.111.113.1")
        wait_dashboard_addresses(stock_b, ["localhost", "10.111.113.1"])

        dev_b.switch_to_top()
        dev_b.switch_to_frame("cockpit1:localhost/dashboard")

        add_machine(dev_b, "10.111.113.5")
        dev_dashboard_addresses.append("10.111.113.5")
        wait_dashboard_addresses(dev_b, dev_dashboard_addresses)

        stock_b.switch_to_top()
        self.check_dbus(stock_b, "10.111.113.1")
        self.check_dbus(dev_b, "10.111.113.5")

        self.check_spawn(stock_b, "10.111.113.1")
        self.check_spawn(dev_b, "10.111.113.5")

        dev_b.switch_to_top()
        dev_b.go("/@10.111.113.5/network")
        dev_b.wait_present("iframe.container-frame[name='cockpit1:10.111.113.5/network'][src$='/network/index.html#/']")

        dev_b.switch_to_top()
        dev_b.go("/@10.111.113.5/storage")
        dev_b.wait_present("iframe.container-frame[name='cockpit1:10.111.113.5/storage'][src$='/storage/index.html#/']")

        dev_b.switch_to_top()
        dev_b.go("/@10.111.113.5/users")
        dev_b.wait_present("iframe.container-frame[name='cockpit1:10.111.113.5/users'][src$='/users/index.html#/']")

        stock_b.switch_to_top()
        stock_b.go("/@10.111.113.1/system")
        stock_b.wait_present("iframe.container-frame[name='cockpit1:10.111.113.1/system'][data-loaded]")
        stock_b.switch_to_frame('cockpit1:10.111.113.1/system')
        stock_b.wait_text_not("#system_information_hardware_text", "")

        # Messages from previous versions of cockpit
        self.allow_journal_messages(".*pam_authenticate failed: Authentication failure")


class TestMultiOSDirect(MachineCase):
    provision = {
        "0": {"address": "10.111.113.1/20"},
        "fedora-23-stock": {"address": "10.111.113.5/20", "image": "fedora-23-stock"}
    }

    def testFedora23Direct(self):
        b = self.browser

        self.allow_hostkey_messages()

        self.login_and_go("/dashboard")

        dev_dashboard_addresses = ["localhost"]
        wait_dashboard_addresses(b, dev_dashboard_addresses)

        stock_m = self.machines['fedora-23-stock']
        stock_m.execute("hostnamectl set-hostname stock")

        add_machine(b, "10.111.113.5")
        dev_dashboard_addresses.append("10.111.113.5")
        wait_dashboard_addresses(b, dev_dashboard_addresses)
        b.logout()

        # Access stock directly from dev
        b.open("/=10.111.113.5")
        b.wait_visible("#login")
        b.wait_not_visible("#badge")
        b.wait_not_visible("#brand")
        b.set_val("#login-user-input", "admin")
        b.set_val("#login-password-input", "foobar")
        b.click('#login-button')
        b.expect_load()

        b.wait_present("iframe.container-frame[name='cockpit1:localhost/system'][data-loaded]")
        b.wait_not_visible(".curtains")
        b.wait_visible("iframe.container-frame[name='cockpit1:localhost/system']")
        b.switch_to_frame("cockpit1:localhost/system")
        b.wait_visible("body")
        b.wait_in_text('#system_information_hostname_button', "stock")
        b.switch_to_top()

        # Branding uses default because there is no os information
        b.wait_not_present("#index-brand.hide-before")

        b.wait_js_cond('window.location.pathname.indexOf("shell/index.html") > -1')


if __name__ == '__main__':
    test_main()
